<template>
  <view class="container">
    <!-- 状态指示器 -->
    <view class="status-indicator">
      <view :class="['status-dot', scannerStatus]"></view>
      <text class="status-text">扫描状态: {{ statusMessage }}</text>
     <!-- <text class="scan-count">扫描计数: {{ scanCount }}</text>-->
    </view>

    <!-- 开始扫码按钮 -->
    <view class="controls">
      <!--<button @click="startScan">开始扫码</button>
      <button @click="stopScan" v-if="isScanning">停止扫码</button>-->
      <button @click="clearHistory">清空历史</button>
    </view>

    <!-- 扫码结果 -->
    <!--<view class="result">
      <text class="result-text">{{ comparisonResult }}</text>
    </view>-->

    <!-- 扫码历史 -->
    <view class="history">
      <text>扫码历史（共{{ group_id - 1 }}组）：</text>
      <scroll-view scroll-y="true" class="history-scroll">
        <view v-for="(item, index) in scanHistory" :key="index" class="history-item">
          <text>{{ item }}</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

const comparisonResult = ref("")
const scanHistory = ref<string[]>([])
const isScanning = ref(false)
const scannerStatus = ref("ready") // ready, scanning, error
const statusMessage = ref("正在初始化扫描功能...")
const scanCount = ref(0)

// 组数ID
let group_id =1
// 缓存两种二维码
let packageCode: string | null = null
let supplierCode: string | null = null

// ================= iData扫描插件相关 =================
// 获取扫描模块和全局事件监听器
let barcodeModel: any = null
let globalEvent: any = null

// 添加防抖相关变量
let lastScanTime = 0
const SCAN_DEBOUNCE_INTERVAL = 300 // 防抖间隔300毫秒
let lastScanBarcode = ""

// 初始化扫描插件
const initScanner = () => {
  // #ifdef APP-PLUS
  try {
    // 获取模块和全局事件
    barcodeModel = uni.requireNativePlugin("iData-BarcodePlugin-BarcodeModule")
    globalEvent = uni.requireNativePlugin('globalEvent')
    
    // 初始化扫描
    barcodeModel.initScan((ret: any) => {
      console.log('扫描初始化结果: ', ret)
      
      if (ret && ret.code === 'success') {
        scannerStatus.value = "ready"
        statusMessage.value = "就绪，可使用物理按键扫描"
        
        // ✅ 启用物理扫描键扫码功能
        barcodeModel.setScanKeyEnable(true, (enableRet: any) => {
          console.log('物理扫描键启用结果: ', enableRet)
          if (enableRet && enableRet.code === 'success') {
            scannerStatus.value = "ready"
            statusMessage.value = "物理按键已启用，可开始扫描"
            
            // 🔧 尝试设置单次扫描模式，避免重复触发
            barcodeModel.continueScan(false, (continueRet: any) => {
              console.log('设置单次扫描模式: ', continueRet)
            })
            
            uni.showToast({
              title: '扫描功能就绪',
              icon: 'success',
              duration: 1500
            })
          } else {
            console.warn('物理扫描键启用可能失败: ', enableRet)
            statusMessage.value = "就绪（物理键功能受限）"
          }
        })
      } else {
        scannerStatus.value = "error"
        statusMessage.value = `扫描初始化失败: ${JSON.stringify(ret)}`
        console.error('扫描初始化失败，返回值: ', ret)
        uni.showToast({
          title: '扫描初始化失败',
          icon: 'error',
          duration: 3000
        })
      }
    })
    
    // 监听扫描事件（添加防抖处理）
    globalEvent.addEventListener('iDataBarcodeEvent', (e: any) => {
      console.log('收到条码数据：', e)
      
      // 🔧 添加防抖逻辑，避免重复处理
      const currentTime = Date.now()
      const currentBarcode = e?.barcode || ""
      
      // 检查是否在防抖时间内且条码内容相同
      if (currentTime - lastScanTime < SCAN_DEBOUNCE_INTERVAL && currentBarcode === lastScanBarcode) {
        console.log('防抖：忽略重复扫描事件')
        return
      }
      
      // 更新最后扫描时间和条码
      lastScanTime = currentTime
      lastScanBarcode = currentBarcode
      scanCount.value++
      
      if (e && e.barcode) {
        handleScanResult(e.barcode)
      } else {
        console.warn('收到扫描事件但数据格式异常: ', e)
      }
    })
  } catch (error) {
    console.error('初始化扫描插件失败:', error)
    scannerStatus.value = "error"
    statusMessage.value = "扫描插件初始化异常"
    uni.showToast({
      title: '扫描功能初始化失败',
      icon: 'none',
      duration: 3000
    })
  }
  // #endif
}

// ================= 工具函数 =================
function asStr(v: any): string {
  return String(v ?? "")
}

function isPackageCode(code: any): boolean {
  const s = asStr(code)
  return s !== "" && s.indexOf("&") === -1
}

function isSupplierCode(code: any): boolean {
  const s = asStr(code)
  return s !== "" && s.indexOf("&") !== -1
}

function extractPackageCodeFromSupplierCode(supplierCode: string): string | null {
  const parts = supplierCode.split("&")
  return parts.length >= 3 ? parts[2] : null
}

function resetCodes() {
  packageCode = null
  supplierCode = null
  scanHistory.value.unshift(`第${group_id}组：${comparisonResult.value}`)
  group_id++
}

// ================= 音频播放器 =================
const successAudio = uni.createInnerAudioContext()
successAudio.src = '/static/audio/success.mp3'

const failAudio = uni.createInnerAudioContext()
failAudio.src = '/static/audio/fail.mp3'

function playSuccessSound() {
  successAudio.stop()
  successAudio.play()
}

function playFailSound() {
  failAudio.stop()
  failAudio.play()
}

// ================= 核心逻辑 =================
function processScannedCode(raw: string) {
  const code = asStr(raw)
  if (code === "") return

  let codeType = ""
  if (isPackageCode(code)) {
    packageCode = code
    codeType = "翻包二维码"
  } else if (isSupplierCode(code)) {
    supplierCode = code
    codeType = "供应商标签二维码"
  } else {
    codeType = "未知二维码"
  }

 // const timestamp = formatDateTime()
  scanHistory.value.unshift(`第${group_id}组：${codeType}: ${code}`)
  // 限制历史记录数量
  if (group_id > 100) {
    scanHistory.value.pop()
  }

  if (packageCode != null && supplierCode != null) {
    const extracted = extractPackageCodeFromSupplierCode(supplierCode as string)
    if (extracted == null) {
      comparisonResult.value = "供应商二维码格式错误"
      playFailSound()
      resetCodes()
      return
    }

    if (extracted === packageCode) {
      comparisonResult.value = "✅"
      playSuccessSound()
      resetCodes()
    } else {
      comparisonResult.value = "❌"
      playFailSound()
      uni.showModal({
        title: "提示",
        content: `比对结果不一致，请检查二维码！
翻包二维码: ${packageCode}
供应商二维码: ${supplierCode}`,
        showCancel: false
      })
      resetCodes()
    }
  }
}

// ================= 扫描入口 =================
function handleScanResult(code: string) {
  processScannedCode(code)
}

// ================= PDA扫码控制 =================
function startScan() {
  // 开始新的比对 → 清空历史
  scanHistory.value = []
  comparisonResult.value = ""
  isScanning.value = true
  scannerStatus.value = "scanning"
  statusMessage.value = "正在扫描中..."
  scanCount.value = 0

  // #ifdef APP-PLUS
  if (barcodeModel) {
    // 开始扫描
    barcodeModel.scanStart((ret: any) => {
      console.log('开始扫描: ', ret)
    })
  }
  // #endif
}

function stopScan() {
  isScanning.value = false
  scannerStatus.value = "ready"
  statusMessage.value = "已停止扫描"
  
  // #ifdef APP-PLUS
  if (barcodeModel) {
    // 停止扫描
    barcodeModel.scanStop((ret: any) => {
      console.log('停止扫描: ', ret)
    })
  }
  // #endif
}

function clearHistory() {
  scanHistory.value = []
  scanCount.value = 0
}

function formatDateTime(date: Date = new Date()): string {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
// 输出：2024-01-15 14:30:25

// ================= 生命周期 =================
onMounted(() => {
  initScanner()
})

onUnmounted(() => {
  // #ifdef APP-PLUS
  if (barcodeModel) {
    // 结束扫描
    barcodeModel.closeScan((ret: any) => {
      console.log('关闭扫描: ', ret)
    })
  }
  
  if (globalEvent) {
    // 移除事件监听
    globalEvent.removeEventListener('iDataBarcodeEvent')
  }
  // #endif
})
</script>

<style>
.container {
  flex: 1;
  flex-direction: column;
  padding: 20rpx;
  height: 100vh;
}

.status-indicator {
  display: flex;
  flex-direction: column;
  margin-bottom: 20rpx;
  padding: 15rpx;
  border-radius: 10rpx;
  background-color: #f9f9f9;
}

.status-line {
  display: flex;
  align-items: center;
  margin-bottom: 5rpx;
}

.status-dot {
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
  margin-right: 15rpx;
}

.status-dot.ready {
  background-color: #4cd964;
}

.status-dot.scanning {
  background-color: #007aff;
}

.status-dot.error {
  background-color: #dd524d;
}

.status-text, .scan-count {
  font-size: 28rpx;
  color: #555;
  margin-right: 20rpx;
}

.controls {
  margin-bottom: 20rpx;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  flex-wrap: wrap;
}

.controls button {
  margin: 5rpx;
  min-width: 200rpx;
}

.result {
  margin-bottom: 20rpx;
  padding: 20rpx;
  background-color: #f9f9f9;
  border-radius: 10rpx;
}

.result-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.history {
  flex: 1;
}

.history-scroll {
  max-height: 700rpx;
  border: 1rpx solid #eee;
  border-radius: 5rpx;
  padding: 10rpx;
}

.history-item {
  padding: 8rpx;
  border-bottom: 1rpx solid #f0f0f0;
  font-size: 24rpx;
  color: #666;
}
</style>